package com.example.edits;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;




public class ListViewActivity extends AppCompatActivity {

    private String[] data = {"Apple", "Banana", "Orange", "Watermelon",
            "Pear", "Grape", "Pineapple", "Strawberry", "Cherry", "Mango"};

    private List<Fruit> fruitList = new ArrayList<Fruit>();;

    private void initFruits() {
        for (int i = 0; i < 50; i++) {
            Fruit apple = new Fruit("Apple"+i, R.drawable.apple);
            fruitList.add(apple);
        }

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);

//        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
//                ListViewActivity.this,
//                android.R.layout.simple_list_item_1,
//                data);
        ListView listView = (ListView) findViewById(R.id.list_view);
//        listView.setAdapter(adapter);

        initFruits();

        FruitAdapter adapter = new FruitAdapter(
                ListViewActivity.this,
                R.layout.fruit_list_item,
                fruitList);

        listView.setAdapter(adapter);

        /**
         * 选中列表项触发
         */
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Fruit fruit = fruitList.get(position);
                Toast.makeText(ListViewActivity.this, fruit.getName(),
                        Toast.LENGTH_SHORT).show();
            }
        });
    }


}
